/**
 * Created by wb-jiadengyu on 2016/2/2.
 */

//mysql 数据库连接信息
var mysqlOpts = {
    'host'     : '127.0.0.1',
    'user'     : 'root',
    'password' : '123456',
    'database' : 'mine',
    'charset'  : 'UTF8'
};
//mongoodb数据库连接信息
var mongodb = {
    url:'mongodb://localhost:27107/test',
    mongodbOptions: {
        server: {
            auto_reconnect: true
        },
        replset: {
            poolSize: 5,
            rs_name: 'cloud-rs'
        }
    }
};

module.exports = function(type){
    if(type == 'mysql'){
        var Pool = require('generic-pool').Pool;
        global.pool = new Pool({
            name     : 'mysql',
            create   : function(callback) {
                var c = require('mysql').createConnection(mysqlOpts);
                c.connect(function(err){
                    if(err){
                        console.error(err);
                        return ;
                    }
                    console.log('create connection ok ...');
                });
                callback(null, c);
            },
            destroy  : function(client) { client.end(); },
            max      : 10,
            min      : 2,
            idleTimeoutMillis : 30000,
            log : false
        });
    }else if (type === 'mongodb'){
        require('mongoose').connect(mongodb.url, mongodb.mongodbOptions, function(err) {
            if (err) {
                console.log('Could not connect to MongoDB!'+mongodb.url);
                console.log(err);
            } else {
                console.log('success mongodb'+mongodb.url+JSON.stringify(dbOption));
            }
        });
        var cacheOpts = {
            max: 5000,
            // debug: true,
            maxAge: 1000 * 10
        };
        require('mongoose-cache').install(mongoose, cacheOpts);
    }else{
        console.error('数据库连接失败');
        exit(1);
    }
};

